package com.batman.baselibrary.widget.update;

import com.batman.baselibrary.delegate.ApplicationDelegate;
import com.batman.baselibrary.delegate.ApplicationDispatcher;
import com.batman.baselibrary.utils.BasePackagePostData;

import org.lzh.framework.updatepluginlib.base.CheckWorker;
import org.lzh.framework.updatepluginlib.model.CheckEntity;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;

/**
 * Created by guqian on 2018/7/12.
 */

public class ChWorker extends CheckWorker {

    private static OkHttpClient client;

//    static HttpLoggingInterceptor logging = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
//        @Override
//        public void log(String message) {
//            Log.d("OKhttp", message);
//        }
//    });

    static {
        client = new OkHttpClient.Builder()
                .connectTimeout(10, TimeUnit.SECONDS)
                .writeTimeout(10, TimeUnit.SECONDS)
                .readTimeout(10, TimeUnit.SECONDS).build();
    }

    @Override
    protected boolean useAsync() {
        return true;
        // 首先复写此方法。指定当前更新请求接口任务应该使用同步还是异步的方式
        // 当返回true：代表使用异步操作。将会触发asyncCheck方法。
        // 当返回false:代表使用同步操作。将会触发check方法
        // 复写对应的
    }

    @Override
    protected String check(CheckEntity entity) throws Exception {
        return "";
    }

    @Override
    protected void asyncCheck(CheckEntity entity) {
        // 此处运行于子线程。可在此使用异步请求方式请求entity更新接口。
        // 当请求失败：需要手动调用onError(Throwable)并传入失败异常
        // 当请求成功：需要手动调用onResponse(String)并传入接口返回原始数据。便于后续解析
        // entity: 检查更新接口的数据实体类。包含url, params, method
        // 此处运行于子线程。可在此直接替换网络框架使用，返回接口所返回的更新数据即可

        RequestBody params = BasePackagePostData.updateCheckAppVersion();
        String url = ((ApplicationDelegate) (ApplicationDispatcher.get().getApplicationContext())).getBaseUrl() + "common-service/updateCheckAppVersion";


        final Request request = new Request.Builder()
                .url(url)
                .post(params)
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                onError(e);
            }

            @Override
            public void onResponse(Call call, okhttp3.Response response) throws IOException {
                String result = response.body().string();
                ChWorker.super.onResponse(result);
            }
        });
    }
}
